package com.ibangnuo.manage.service.wxpay;


import com.alibaba.fastjson.JSONObject;
import com.ibangnuo.framework.domain.CommercialTenant;
import com.ibangnuo.framework.domain.CommercialTenantDetailsWx;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.ObjectResult;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.framework.utils.SHA256Uti;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.dao.wxpay.CommercialTenantDetailsWxMapper;
import com.ibangnuo.manage.dao.wxpay.CommercialTenantDetailsWxRepository;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.Optional;


/**
 * @Author: wwy
 * @Date: 2020-01-18 10:33
 */
@Service
public class WxMerchantsIntoPiecesService {
    private static Logger LOGGER = LoggerFactory.getLogger(WxMerchantsIntoPiecesService.class);
    @Autowired
    private RestTemplate restTemplate;
    //商户号
    private String mchid ="";
    //证书序列号
    private String serial_no ="";
    //私钥
    private String rsaPrivateKey ="";
    //证书文件
    private String privateKeyFilePath = "";
    @Autowired
    private CommercialTenantDetailsWxRepository commercialTenantDetailsWxRepository;
    @Autowired
    private CommercialRepository commercialRepository;
    @Autowired
    private CommercialTenantDetailsWxMapper commercialTenantDetailsWxMapper;


    /**
     * 图片上传接口调用
     * 1.保存图片到本地，保存web地址到数据库，回显使用
     * 2.调用上传图片接口，保存返回的结果
     * @param file
     */
    public Map<String,String> uploadImg(MultipartFile file){
        String body = this.uploadImgResult(file);
        Map<String,String> map = JSONObject.parseObject(body, Map.class);
        return map;
    }
    public String uploadImgResult(MultipartFile file){
        String url = "https://api.mch.weixin.qq.com/v3/merchant/media/upload";
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            //拼接签名串
            String fileSha256 = DigestUtils.sha256Hex(file.getInputStream());//文件sha256值
            String timestamp = Long.toString(System.currentTimeMillis()/1000);
            String nonce_str = Long.toString(PrimaryKeyUtil.nextId());//随机数
            String fileName = file.getOriginalFilename();
            int indexOf = fileName.lastIndexOf(".");
            String fileType = fileName.substring(indexOf);
            String filename = System.currentTimeMillis()+fileType;
            StringBuffer sb =new StringBuffer();
            sb.append("POST").append("\n");
            sb.append("/v3/merchant/media/upload").append("\n");
            sb.append(timestamp).append("\n");
            sb.append(nonce_str).append("\n");
            sb.append("{\"filename\":\""+filename+"\",\"sha256\":\""+fileSha256+"\"}").append("\n");
            LOGGER.info("待签名字符串",sb.toString());
            //计算签名
            String sign = new String(Base64.encodeBase64(SHA256Uti.signRSA(sb.toString(),rsaPrivateKey)));
            LOGGER.info("签名值{}",sign);
            //拼装authorization头
            String authorization ="WECHATPAY2-SHA256-RSA2048 mchid=\""+mchid+"\",nonce_str=\""+nonce_str+"\",signature=\""+sign+"\",timestamp=\""+timestamp+"\",serial_no=\""+serial_no+"\"";
            MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
            LOGGER.info("authorization内容:{}",authorization);
            headers.add("Accept","application/json");
            headers.add("Content-Type","multipart/form-data");
            headers.add("Authorization", authorization);
            //拼接body
            MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
            requestBody.add("Accept","application/json");
            requestBody.add("Content-Type","multipart/form-data");
            requestBody.add("Authorization", authorization);
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> rsponseEntity = restTemplate.postForEntity(url, request, String.class);
            String body = rsponseEntity.getBody();
            LOGGER.info("图片上传body内容:{}",body);
        } catch (IOException e) {
            LOGGER.error("图片获取io错误",e.getMessage());
        } catch (Exception e) {
            LOGGER.error("图片获取io错误",e.getMessage());
        }
        return null;
    }

    /**
     * 微信商户进件商户进件
     * @param id 商户id
     * @return
     */
    public ObjectResult applyment(String id){
        CommercialTenant commercialTenant = this.getById(id);
        if(commercialTenant == null){
            return new ObjectResult(CommonCode.FAIL,null);
        }
        Map<String, Object> commercialTenantDetailsMap = commercialTenantDetailsWxMapper.findByCommercialId(commercialTenant.getId());
        if(commercialTenantDetailsMap == null){
            return new ObjectResult(CommonCode.FAIL,null);
        }
        return null;

    }

    /**
     * 商户进件接口调用
     * @param commercialTenantDetailsMap
     * @return
     */
    private Map<String,String> applymentResult(Map<String, Object> commercialTenantDetailsMap){
        String url = "/v3/applyment4sub/applyment";
        WechatPayHttpClientBuilder builder;
        try {
            builder = WechatPayHttpClientBuilder.create()
                    .withMerchant(mchid, serial_no, PemUtil.loadPrivateKey(new FileInputStream(privateKeyFilePath)));
            HttpClient httpClient = builder.build();
            HttpPost httpPost = new HttpPost(url);
            String contact_info = String.valueOf(commercialTenantDetailsMap.get("contact_info"));//超级管理员信息
            Map mapContactInfo = JSONObject.parseObject(contact_info, Map.class);
            commercialTenantDetailsMap.put("contact_info",mapContactInfo);

            String mapSubjectInfo = String.valueOf(commercialTenantDetailsMap.get("subject_info"));//主体资料
            commercialTenantDetailsMap.put("subject_info",mapSubjectInfo);

            String mapBusinessInfo = String.valueOf(commercialTenantDetailsMap.get("business_info"));//经营资料
            commercialTenantDetailsMap.put("business_info",mapBusinessInfo);

            String mapSettlementInfo = String.valueOf(commercialTenantDetailsMap.get("settlement_info"));//结算规则
            commercialTenantDetailsMap.put("settlement_info",mapSettlementInfo);

            String mapBankAccountInfo = String.valueOf(commercialTenantDetailsMap.get("bank_account_info"));//结算银行账户
            commercialTenantDetailsMap.put("bank_account_info",mapBankAccountInfo);

            String mapAdditionInfo = String.valueOf(commercialTenantDetailsMap.get("addition_info"));//补充材料
            commercialTenantDetailsMap.put("addition_info",mapAdditionInfo);

            String jsonString = JSONObject.toJSONString(commercialTenantDetailsMap);

            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            String responseStr = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            return JSONObject.parseObject(responseStr,Map.class);
        } catch (FileNotFoundException e) {
            LOGGER.error("商户进件接口调用证书文件获取错误",e.getMessage());
        } catch (ClientProtocolException e) {
            LOGGER.error("商户进件接口调用请求异常",e.getMessage());
        } catch (IOException e) {
            LOGGER.error("商户进件接口调用IO错误",e.getMessage());
        }

        return null;
    }

    /**
     * 商户进件添加
     * @param commercialTenantDetailsWx
     * @return
     */
    public ObjectResult add(CommercialTenantDetailsWx commercialTenantDetailsWx){
        if(StringUtils.isEmpty(commercialTenantDetailsWx.getId())){
            commercialTenantDetailsWx.setCreateTime(new Date());
        }
        commercialTenantDetailsWx.setUpdateTime(new Date());
        commercialTenantDetailsWxRepository.save(commercialTenantDetailsWx);
        return new ObjectResult(CommonCode.SUCCESS,null);
    }

    /**
     * 根据id查询进件
     * @param id
     * @return
     */
    public ObjectResult findById(String id){
        Optional<CommercialTenantDetailsWx> optional = commercialTenantDetailsWxRepository.findById(id);
        if(optional.isPresent()){
            return new ObjectResult(CommonCode.SUCCESS,optional.get());
        }
        return new ObjectResult(CommonCode.FAIL,null);
    }

    /**
     * 根据商户id查询微信进件
     * @param commercialId
     * @return
     */
    public ObjectResult findByCommercialId(String commercialId){
        CommercialTenantDetailsWx commercialTenantDetailsWx = commercialTenantDetailsWxRepository.findByCommercialTenantId(commercialId);
        if(commercialTenantDetailsWx == null){
            return new ObjectResult(CommonCode.FAIL,null);
        }
        return new ObjectResult(CommonCode.SUCCESS,commercialTenantDetailsWx);
    }

    /**
     * 查询商户
     * @param id
     * @return
     */
    private CommercialTenant getById(String id){
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }





}
